<template>
  <el-dialog @close="close" v-model="dialogVisible" :title="title" width="50%" align-center>
    <el-scrollbar height="70vh">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="平台名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="平台介绍" prop="introduction">
          <el-input v-model="ruleForm.introduction" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="地区" prop="area">
          <el-cascader
            v-model="ruleForm.area"
            :options="optionsnative_place"
            :props="{ label: 'label', value: 'label', children: 'children' }"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="ruleForm.username"
            :disabled="ruleForm && ruleForm.id ? true : false"
            placeholder="请输入用户名,用于登录"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!ruleForm.id">
          <el-input v-model="ruleForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input
            v-model="ruleForm.mobile"
            :disabled="ruleForm && ruleForm.id ? true : false"
            placeholder="请输入电话"
          />
        </el-form-item>
        <el-form-item label="强制时长" prop="config">
          <el-input
            v-model="ruleForm.config.mandatory_time"
            placeholder="请输入强制时长"
            type="number"
          >
            <template #append>时（H）</template>
          </el-input>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="ruleForm.level" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in 7" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期时间" prop="mobile">
          <el-date-picker
            v-model="ruleForm.endtime"
            type="date"
            placeholder="请选择到期时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="ruleForm.status"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="二维码" prop="qrcode">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :http-request="httpRequest"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="addFileMain"
          >
            <img v-if="ruleForm.qrcode" :src="ruleForm.qrcode" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="地图定位" prop="position">
          <el-input
            v-model="ruleForm.position"
            disabled
            placeholder="请选择位置"
            style="margin-bottom: 10px"
          />
          <baidu-map
            class="map"
            :center="{ lng: 116.404, lat: 39.915 }"
            :zoom="15"
            :scroll-wheel-zoom="false"
            @click="bindMapPosition"
          >
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-marker :position="position" :dragging="true" v-if="position"></bm-marker>
          </baidu-map>
        </el-form-item>

        <el-form-item label="appid" prop="appid">
          <el-input v-model="ruleForm.appid" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="appsecret" prop="appsecret">
          <el-input v-model="ruleForm.appsecret" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleClose(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ElMessageBox, ElMessage, FormInstance, ElNotification } from 'element-plus'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { addPlatform, editPlatform, uploadFun, validateUser } from '@/api/admin'
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from 'element-china-area-data'
const optionsnative_place = regionData

const authArr = ref()
const saveLoading = ref(false)
const ruleFormRef = ref<FormInstance>()
const dialogVisible = ref<boolean>(false)
const title = ref('新增平台')
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请填写用户名'))
  } else if (value.length < 6) {
    callback(new Error('用户名不能小于6位'))
  } else {
    validateUser({ username: value }).then((res) => {
      if (res.code == 200) {
        if (!res.data) {
          callback(new Error('用户名已存在'))
        }
      }
    })
  }
  callback()
}
const validatePassal = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请填写用户名'))
  } else if (value.length < 6) {
    callback(new Error('用户名不能小于6位'))
  } else {
    validateUser({ username: value }).then((res) => {
      if (res.code == 200) {
        if (!res.data) {
          callback(new Error('用户名已存在'))
        }
      }
    })
  }
  callback()
}
const rules = reactive({
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  // username: [{ required: true, message: '请输入', trigger: 'blur' }],
  username: [{ required: true, validator: validatePass, trigger: 'blur' }],
  password: [{ required: true, message: '请输入', trigger: 'blur' }],
  mobile: [{ required: true, message: '请输入', trigger: 'blur' }],
  qrcode: [{ required: true, message: '请上传', trigger: 'change' }],
  level: [{ required: true, message: '请选择', trigger: 'change' }],
  area: [{ required: true, message: '请选择', trigger: 'change' }],
  position: [{ required: true, message: '请选择', trigger: 'change' }],
})

const ruleForm = reactive({
  id: '',
  appid: '',
  appsecret: '',
  name: '',
  introduction: '',
  username: '',
  password: '',
  status: 1,
  level: '',
  mobile: '',
  area: '',
  qrcode: '',
  position: '',
  endtime: '',
  config:{
    mandatory_time:''
  }
})

const emit = defineEmits<{ (event: 'refresh'): void }>()

function close() {
  ruleFormRef.value.resetFields()
  Object.keys(ruleForm).forEach((key) => {
    if (key == 'status') ruleForm[key] = 1
    else ruleForm[key] = ''
  })
  position.value = null
}

const show = (item = {}) => {
  title.value = '新增平台'
  if (item.id) {
    item.password = ''
    title.value = '编辑平台'
    Object.keys(ruleForm).forEach((key) => {
      if (key == 'area') ruleForm[key] = item[key].split(',')
      else if (key == 'position') {
        ruleForm[key] = item[key]
        position.value = {
          lng: item.position.split(',')[0],
          lat: item.position.split(',')[1],
        }
      }else if (key == 'config' && !item[key]) {
        ruleForm[key] = {mandatory_time:''}
      }else ruleForm[key] = item[key]
    })
  }
  dialogVisible.value = true
}

const handleClose = async (done: () => void) => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      ruleForm.area = ruleForm.area.join(',')
      saveLoading.value = true
      if (ruleForm.id) {
        //编辑
        editPlatform(ruleForm).then((res) => {
          if (res.code == 200) {
            ElNotification({
              title: '编辑成功',
              message: res.msg,
              type: 'success',
            })
            emit('refresh')
          }
          dialogVisible.value = false
          saveLoading.value = false
        })
      } else {
        //新增
        addPlatform(ruleForm).then((res) => {
          if (res.code == 200) {
            ElNotification({
              title: '添加成功',
              message: res.msg,
              type: 'success',
            })
            emit('refresh')
          }
          dialogVisible.value = false
          saveLoading.value = false
        })
      }
    }
  })
}

const httpRequest = (file) => {}
const addFileMain = (file) => {
  let raw = file.raw
  let formDate = new FormData()
  formDate.append('file', raw)
  formDate.append('timestamp', '12345678910')
  formDate.append('nonceStr', 'nonceStr')
  formDate.append('sign', 'sign')
  if (raw != null) {
    uploadFun(formDate).then((res) => {
      if (res.code == 200) {
        ruleForm.qrcode = res.data.url
        console.log('ruleForm.qrcode', ruleForm.qrcode)
      }
    })
  }
}

const handleAvatarSuccess = (response, uploadFile) => {
  console.log('succeess', response, uploadFile)
  // ruleForm.qrcode = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload = (rawFile) => {
  console.log('rawFile', rawFile)
}

const position = ref()
const bindMapPosition = (val) => {
  position.value = val.point
  ruleForm.position = position.value.lng + ',' + position.value.lat
}

defineExpose({
  show,
})
</script>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
.map {
  width: 100%;
  height: 240px;
}
</style>

